class Solution {
public:
    int findroot(vector<int>& ufs,int i){
         while(ufs[i] >= 0){
            i = ufs[i];
        }
        return i;
    }
    int findCircleNum(vector<vector<int>>& isConnected) {
        vector<int> ufs(isConnected.size(),-1);
        for(int i = 0;i < isConnected.size();i++){
            for(int j = 0;j < isConnected.size();j++){
                if(i != j && isConnected[i][j] == 1){
                    int root1 = findroot(ufs,i);
                    int root2 = findroot(ufs,j);
                    if(root1 != root2){
                        ufs[root1] += ufs[root2];
                        ufs[root2] = root1;
                    }
                    isConnected[j][i] = 0;
                }
            }
        }
        int num = 0;
        for(int n : ufs){
            if(n < 0){
                num ++;
            }
        }
        return num;
    }
};
